package com.kaige.asktaoplugin60.handler;

import com.kaige.asktaoplugin60.config.GameConfig;
import com.kaige.asktaoplugin60.config.PluginConfig;
import com.kaige.asktaoplugin60.utils.ClientUtil;
import com.kaige.asktaoplugin60.utils.ConnectionManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.ChannelHandler.Sharable;
import lombok.extern.slf4j.Slf4j;

/**
 * 插件服务端处理器 - 处理来自玩家客户端的连接
 */
@Slf4j
@Sharable
public class PluginServerHandler extends ChannelInboundHandlerAdapter {
    
    private final GameConfig gameConfig;
    private final PluginConfig pluginConfig;
    
    // 线路端口
    private Integer linePort;
    
    public PluginServerHandler(GameConfig gameConfig, PluginConfig pluginConfig) {
        this.gameConfig = gameConfig;
        this.pluginConfig = pluginConfig;
    }
    
    public void setLinePort(Integer linePort) {
        this.linePort = linePort;
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel clientChannel = ctx.channel();
        log.info("新的客户端连接: {}", clientChannel.remoteAddress());

        // 创建插件客户端处理器
        PluginClientHandler pluginClientHandler = new PluginClientHandler(clientChannel);
        pluginClientHandler.setPluginConfig(pluginConfig);
        pluginClientHandler.setGameConfig(gameConfig);

        // 确定连接的游戏服务端端口
        int targetPort = (linePort != null) ? linePort : gameConfig.getPort();
        
        // 连接到游戏服务端
        Object[] result = ClientUtil.connectToGameService(
                gameConfig.getIp(),
                targetPort,
                pluginClientHandler
        );

        Channel gameServerChannel = (Channel) result[0];
        NioEventLoopGroup nioEventLoopGroup = (NioEventLoopGroup) result[1];

        if (gameServerChannel != null && gameServerChannel.isActive()) {
            log.info("成功连接到游戏服务端: {}:{}", gameConfig.getIp(), targetPort);
            
            // 建立连接映射关系
            ConnectionManager.bind(clientChannel, gameServerChannel);

            // 更新客户端处理器，设置服务端通道
            clientChannel.pipeline().replace(this, "pluginClientHandler", new PlayerConnectionHandler(gameServerChannel));
        } else {
            log.error("无法连接到游戏服务端: {}:{}", gameConfig.getIp(), targetPort);
            clientChannel.close();
            if (nioEventLoopGroup != null) {
                nioEventLoopGroup.shutdownGracefully();
            }
        }
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel clientChannel = ctx.channel();
        log.info("客户端连接断开: {}", clientChannel.remoteAddress());
        
        // 解除连接映射关系
        ConnectionManager.unbind(clientChannel);
        
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("处理客户端连接时发生异常", cause);
        ctx.close();
    }
}